package it.intecs.pisa.smarcos.activities;

import it.intecs.pisa.smarcos.R;
import it.intecs.pisa.smarcos.base.BeepManager;
import it.intecs.pisa.smarcos.base.Downloads;
import it.intecs.pisa.smarcos.base.GestureEvents;
import it.intecs.pisa.smarcos.base.GestureIntents;
import it.intecs.pisa.smarcos.base.SpeechManager;
import it.intecs.pisa.smarcos.util.MathUtils;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class Maria extends BaseActivity {

	public static final String INTENT_SHOW="it.intecs.pisa.smarcos.activities.Maria.SHOW";
	private static final String TAG = Maria.class.getSimpleName();

	private SpeechManager speechManager;

	// Common to all features
	View view; 
	private Vibrator vibrator;
	private BeepManager beepManager;
	private ViewGroup baseCenterView;
	private String position;
	LayoutInflater inflater;
	private String repeat; 
	private int rows = 0;
	private int columns = 0;
	private int i=0;
	private int j=-1;
	private boolean start_i = false;
	private boolean start_j = false;
	private boolean end_i = false;
	private boolean end_j = false;
	private TextView textBody;
	private String cellContent;
	private String columnName;
	private String mariaXmlUrl;
	private File localFile;
	
	private String[][] localTable;
	float startX,startY;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Log.d(TAG, "OnCreate");

		speechManager = SpeechManager.getInstance(getApplicationContext());
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		beepManager = BeepManager.getInstance(getApplicationContext());
		
		Intent intent = getIntent();
		mariaXmlUrl = intent.getStringExtra("MariaFileUrl");
				
		retrieveFile();
		createLocalTable();

		// Metodo di BaseViewManager
		Init(getBaseContext());
		inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
		view = inflater.inflate(R.layout.table_cell, null);
		setContentView(getBaseView());
		baseCenterView = (ViewGroup) findViewById(R.id.center_base_view);
		baseCenterView.addView(view);

		position = getString(R.string.TTS_MARIA_Position) + ": " + rows + " " + getString(R.string.TTS_MARIA_Rows_Number)+ " " + columns + " " + getString(R.string.TTS_MARIA_Columns_Number);	
		
		speechManager.say(getString(R.string.TTS_MARIA_Columns_Swipe), true, false);
		speechManager.say(getString(R.string.TTS_MARIA_Rows_Swipe), true, false);
		
		textBody = (TextView) findViewById(R.id.MariaText);
	}

	
	private void retrieveFile(){
		
		Log.d(TAG, "retrieveFile");
		Downloads d = new Downloads(getBaseContext());
		
		d.download(mariaXmlUrl, "description", "title");
		
		
		File externalDir=Environment.getExternalStorageDirectory();
		File MariaDir=new File(externalDir,"Download");
		File mariaxml=new File(MariaDir,"name-of-the-file.ext");
		
		localFile = new File(mariaxml.getAbsolutePath());
		
		Log.d(TAG, localFile.toString());
		
	}

	@Override
	public void onResume(){
		super.onResume();
		speechManager.say(R.string.MV_Maria_Interpreter);
	}
	
	@Override
	public void onPause() {
		super.onPause();
		Log.d(TAG, "OnPause");	
	}

	// CLOSE
	@Override
	public void onClick_A(){
		Log.d(TAG, "onClick_A");

		Intent returnIntent;
		returnIntent=new Intent("it.intecs.pisa.smarcos.services.ResultReceiver.SHOW");
		returnIntent.putExtra("Result", "NORESULT");
		returnIntent.addCategory(Intent.CATEGORY_DEFAULT);					
		sendBroadcast(returnIntent);
		sentResult = true;
		vibrator.vibrate(300);
		finish();
	}

	// POSITION
	@Override
	public void onClick_B(){
		Log.d(TAG, "onClick_B");
		if(position != null){
			speechManager.say(position, false, false);	
			int j;
			for (j=0; j<columns-1; j++)
				speechManager.say(localTable[0][j], false, false);	
		}
	}

	// REPEAT
	@Override
	public void onClick_C(){
		Log.d(TAG, "onClick_C");
		if (i == 0)
			repeat = columnName + " " + getString(R.string.TTS_MARIA_Row_Number) + (i+1) + 
			" " + getString(R.string.TTS_MARIA_Column_Number) + (j+1);
		else
			repeat = columnName + " " + cellContent + " " + getString(R.string.TTS_MARIA_Row_Number) + (i+1) + 
			" " + getString(R.string.TTS_MARIA_Column_Number) + (j+1);
		
		speechManager.say(repeat, false, false);	
	}

	// DONE -> as CLOSE 
	@Override
	public void onClick_D(){
		Log.d(TAG, "onClick_D");
		onClick_A();
	}


	@Override
	public void onClick_Center(int event, float X, float Y){
		Log.d(TAG, "onClick_Center");

		float lenghtTreshold=10;

		switch(event)
		{
		case GestureEvents.ONFLING_START:

			startX = X;
			startY = Y;
			break;

		case GestureEvents.ONFLING_STOP:

			float endX,endY;

			endX = X;
			endY = Y;

			float gestureLenght=0;

			gestureLenght=MathUtils.distanceBetweenPoints(endX,startX,endY,startY);

			if(gestureLenght>lenghtTreshold){

				String gesture = MathUtils.calculateSlice(endX,startX,endY,startY);
				if (gesture.length() != 0)
					if (gesture.equals(GestureIntents.INTENT_GESTURE_RIGHT)){

						if (j == -1){ 
							j = 0;
							columnName = localTable[0][j];
							cellContent = localTable[i][j];
							textBody.setText(cellContent);
							
							speechManager.say(cellContent, false, false);
							start_j = false;
							break;
						}
						
						if (j == columns - 1){ 
							end_j = true;
							beepManager.playBeepSound(); 
							break;
						}
						
						if (start_j == true){
							start_j = false;
							j = 0;
							columnName = localTable[0][j];
							cellContent = localTable[i][j];
							textBody.setText(cellContent);
							
							speechManager.say(cellContent, false, false);
							break;
						}
						
						if (end_j == true){
							beepManager.playBeepSound(); 
							break;
						}
						
						j++;
						columnName = localTable[0][j];
						cellContent = localTable[i][j];
						textBody.setText(cellContent);
						
						speechManager.say(cellContent, false, false);
					}
					else if(gesture.equals(GestureIntents.INTENT_GESTURE_LEFT)){

						if (j == -1){ 
							start_j = true;
							beepManager.playBeepSound(); 
							break;
						}
						
						if (j == 0){
							start_j = true;
							beepManager.playBeepSound(); 
							break;
						}
						
						if (start_j == true){ 
							beepManager.playBeepSound(); 
							break;
						}
						
						if (end_j == true){
							end_j = false;
							j = columns - 1;
							columnName = localTable[0][j];
							cellContent = localTable[i][j];
							textBody.setText(cellContent);
							
							speechManager.say(cellContent, false, false);
							break;
						}

						
						j--;
						columnName = localTable[0][j];
						cellContent = localTable[i][j];
						textBody.setText(cellContent);
						
						speechManager.say(cellContent, false, false);

					} 
					else if(gesture.equals(GestureIntents.INTENT_GESTURE_DOWN)){
						if (j == -1)
							j = 0;
						
						if (i < rows - 1 ){	
							if (start_i == false)
								i++;
							else
								start_i = false;
							
							start_j = false;
							end_j = false;
							
							speechManager.say(getString(R.string.TTS_MARIA_Row_Number) + (i+1), false, false);
							cellContent = localTable[i][j];
							textBody.setText(cellContent);
							
							speechManager.say(cellContent, false, false);
						}else{								
							end_i = true;
							beepManager.playBeepSound(); 
						}
					}
					else if(gesture.equals(GestureIntents.INTENT_GESTURE_UP)){
						
						if (j == -1)
							j = 0;
						
						if (i > 0){	
							if (end_i == false)
								i--;
							else 
								end_i = false;		
						
							start_j = false;
							end_j = false;
						
							speechManager.say(getString(R.string.TTS_MARIA_Row_Number) + (i+1), false, false);
							cellContent = localTable[i][j];
							textBody.setText(cellContent);
							
							speechManager.say(cellContent, false, false);
						}else{
							start_i = true;
							beepManager.playBeepSound();
						}
					}
			}
			break;

		case GestureEvents.ONSCROLL:
			if (passBy == true)
				speechManager.say(position, false, false);
			break;
		}
	}

	private void createLocalTable(){
	//private void createLocalTable(InputStream localFile){
		
		Document document;
		Element elementNode;
		Node nodeNode;
		
		try {
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(localFile);
			
		} catch (SAXException e) {
			Log.d(TAG,"Error in menu.xml definition - SAXException " + e);
			return ;
		} catch (IOException e) {
			Log.d(TAG,"Error in menu.xml definition - IOException " + e);
			return ;
		} catch (ParserConfigurationException e) {
			Log.d(TAG,"Error in menu.xml definition - ParserConfigurationException " + e);
			return ;
		}
		
		
		elementNode = document.getDocumentElement(); // the document root
				
		NodeList nodes2;
		NodeList nodes = elementNode.getElementsByTagName("table");
		if (nodes.getLength() == 0){
			Log.d(TAG, "ERROR: no table inside MARIA file");
			return;
		}
			
		nodeNode = nodes.item(0);
		elementNode = (Element) nodeNode;
		
		nodes = elementNode.getElementsByTagName("body");
		if (nodes.getLength() == 0){
			Log.d(TAG, "ERROR: no body table inside MARIA file");
			return;
		}
			
		nodeNode = nodes.item(0);
		elementNode = (Element) nodeNode;
		
	
		 nodes = nodeNode.getChildNodes();
		 boolean firstEl = true;
		 for(int i=0; i < nodes.getLength(); i++){

			 if(nodes.item(i) instanceof Element){
				 rows++;

				 if (firstEl){
					 firstEl = false;
					 nodes2 = nodes.item(i).getChildNodes();

					 for(int j=0; j < nodes2.getLength(); j++){

						 if(nodes2.item(j) instanceof Element){
							 columns++;
						 }
					 }
				 }
			 }
		 }
		 Log.d(TAG, "Number of rows " + rows);
		 Log.d(TAG, "Number of columns " + columns);

		 localTable = new String[rows][columns];

		 int row_i = 0;
		 int column_j = 0;
		 for(int i=0; i < nodes.getLength(); i++){

			 if(nodes.item(i) instanceof Element){
				 
				 nodes2 = nodes.item(i).getChildNodes();
				 column_j = 0;
				 for(int j=0; j < nodes2.getLength(); j++){

					 if(nodes2.item(j) instanceof Element){
						 
						 Element el = (Element) nodes2.item(j);
						 NodeList stringNodes = el.getElementsByTagName("string");	 
						 Log.d(TAG, row_i + " " + column_j);
						 localTable[row_i][column_j] = stringNodes.item(0).getFirstChild().getNodeValue();
						 Log.d(TAG, localTable[row_i][column_j]);
						 column_j++;
					 }
				 }
				 row_i++;
			 }
		 }

	}

}
